import React from "react";
import {Tabs, TabsProps, Avatar, List, Progress, Button} from "antd";
import dayjs from 'dayjs';
import {useEffect, useState} from 'react';
import './SynList.css'
import {
    FolderOutlined,
    FileOutlined,
} from '@ant-design/icons';

const SynList: React.FC = () => {
    const [listData, setListData] = useState([])
    const updateListData = (updatedInfo) => {
        setListData(updatedInfo);
    };
    // 模拟 componentDidMount
    useEffect(() => {
        console.log('componentDidMount');
        connectWebSocket()
        return () => {
            // 清理工作
            console.log('清理工作')
            closeWebSocket()
        }
    }, []);

    const data = [];
    const initdata = () => {
        for (let i = 0; i < 20; i++) {
            data.push({title: 'Ant Design Title' + i})
        }
    }
    initdata()

    let websocket, reconnectTimer
    const connectWebSocket = () => {
        websocket = new WebSocket('ws://localhost:8081/synClientSocket');

        websocket.onopen = () => {
            console.log('WebSocket connected');
            // 可以在连接成功后执行其他逻辑
        };
        websocket.onmessage = (message) => {
            let jsonData = JSON.parse(message.data);
            let messageCode = jsonData.messageCode;
            let logs = jsonData.logs;
            console.log(logs);
            switch (messageCode) {
                case "10001"://刚连接上的消息
                    updateListData(logs)
                    break;
                case "10002"://文件内容变动消息
                    updateListDataItemValue(logs[0].id, logs[0].progress)
                    break;
                case "10003"://服务端推送了新的消息
                    pushListDataItem(logs[0])
                    break;
                default:
            }
            scrollInfo()
        };

        websocket.onclose = () => {
            console.log('WebSocket disconnected');
            // 设置定时器，在一定时间后尝试重新连接
            reconnectTimer = setTimeout(() => {
                // connectWebSocket();
            }, 5000);
        };

        websocket.onerror = (error) => {
            console.error('WebSocket error:', error);
        };
    }

    const closeWebSocket = () => {
        if (websocket) {
            websocket.close();
            websocket = null;
        }

        if (reconnectTimer) {
            clearTimeout(reconnectTimer);
            reconnectTimer = null;
        }
    }
    // updateListData([666])
    const updateListDataItemValue = (id, progress) => {
        setListData(prevItems => {
            return prevItems.map(item => {
                if (item.id === id) {
                    return { ...item, progress: progress };
                }
                return item;
            });
        });
        console.log('updateListDataItemValue',id, progress)
    };
    const pushListDataItem = (item) => {
        delete item.key
        setListData((old)=>[...old,item])
    }

    const scrollInfo=()=>{
        const element = document.getElementById("myList");
        if (element) {
            element.scrollTop = element.scrollHeight
        }
    }
    return <>
        <List
            id="myList"
            itemLayout="horizontal"
            dataSource={listData}
            style={{height: 500, 'overflowY': 'scroll',}}
            renderItem={(item, index) => (
                <List.Item>
                    <List.Item.Meta
                        // avatar={<FolderOutlined style={{fontSize:30,color:'#196ae5'}}/> }
                        avatar={item.fileType != 0 ? <FileOutlined style={{fontSize: 30, color: '#196ae5'}}/> :
                            <FolderOutlined style={{fontSize: 30, color: '#196ae5'}}/>}
                        title={item.name}
                        description={<>
                            {dayjs(item.time).format("YYYY-MM-DD HH:mm:ss")}
                            <Progress percent={item.progress}/>
                        </>}
                    />
                </List.Item>
            )}
        />

    </>
}
export default SynList
